package com.imis.base.shiro.util;


import com.imis.base.util.SpringContextUtils;
import com.imis.base.shiro.vo.SysPermissionDataRule;
import com.imis.base.shiro.vo.SysUserCacheInfo;
import org.apache.shiro.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * DataAuthorUtils<br>
 * 数据权限查询规则容器工具类
 * </p>
 *
 * @author XinLau
 * @version 1.0
 * @since 2019年03月26日 11:11
 */
public class DataAuthorUtils {
	
	public static final String MENU_DATA_AUTHOR_RULES = "MENU_DATA_AUTHOR_RULES";
	
	public static final String MENU_DATA_AUTHOR_RULE_SQL = "MENU_DATA_AUTHOR_RULE_SQL";
	
	public static final String SYS_USER_INFO = "SYS_USER_INFO";

	/**
	 * TODO:This 数据权限查询规则容器工具类
	 */

    /**
    * @Description:  往链接请求里面，传入数据查询条件
    * @Param: [request, dataRules]
    * @return: void
    * @Author: ShaQingjun
    * @Date: 2020/3/3
    */
	public static synchronized void installDataSearchCondition(HttpServletRequest request, List<SysPermissionDataRule> dataRules) {
		@SuppressWarnings("unchecked")
		// 1.先从request获取MENU_DATA_AUTHOR_RULES，如果存则获取到LIST
		List<SysPermissionDataRule> list = (List<SysPermissionDataRule>)loadDataSearchConditon();
		if (list == null) {
			// 2.如果不存在，则new一个list
			list = new ArrayList<SysPermissionDataRule>();
		}
		for (SysPermissionDataRule tsDataRule : dataRules) {
			list.add(tsDataRule);
		}
		// 3.往list里面增量存指
		request.setAttribute(MENU_DATA_AUTHOR_RULES, list);
	}

    /**
    * @Description: 获取请求对应的数据权限规则
    * @Param: []
    * @return: List<SysPermissionDataRule>
    * @Author: ShaQingjun
    * @Date: 2020/3/3
    */
	@SuppressWarnings("unchecked")
	public static synchronized List<SysPermissionDataRule> loadDataSearchConditon() {
		return (List<SysPermissionDataRule>) SpringContextUtils.getHttpServletRequest().getAttribute(MENU_DATA_AUTHOR_RULES);
				
	}

    /**
    * @Description:  获取请求对应的数据权限SQL
    * @Param: []
    * @return: java.lang.String
    * @Author: ShaQingjun
    * @Date: 2020/3/3
    */
	public static synchronized String loadDataSearchConditionSqlString() {
		return (String) SpringContextUtils.getHttpServletRequest().getAttribute(MENU_DATA_AUTHOR_RULE_SQL);
	}

    /**
    * @Description:  往链接请求里面，传入数据查询条件
    * @Param: [request, sql]
    * @return: void
    * @Author: ShaQingjun
    * @Date: 2020/3/3
    */
	public static synchronized void installDataSearchCondition(HttpServletRequest request, String sql) {
		String ruleSql = loadDataSearchConditionSqlString();
		if (!StringUtils.hasText(ruleSql)) {
			request.setAttribute(MENU_DATA_AUTHOR_RULE_SQL, sql);
		}
	}
	
	public static synchronized void installUserInfo(HttpServletRequest request, SysUserCacheInfo userinfo) {
		request.setAttribute(SYS_USER_INFO, userinfo);
	}
	
	public static synchronized SysUserCacheInfo loadUserInfo() {
		return (SysUserCacheInfo) SpringContextUtils.getHttpServletRequest().getAttribute(SYS_USER_INFO);
	}

}
